// 8. Loading框，通过showDialog+AlertDialog实现
import 'dart:math';

import 'package:get/get.dart';
import 'package:flutter_base_app/config/app_colors.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:flutter_smart_dialog/src/kit/view_utils.dart';
import 'package:flutter_base_app/config/i18n/i18n.dart';
import 'package:flutter_base_app/config/i18n/i18n_key.dart';

final _loadTags = <String>[];

///是否已经存在显示的loading
bool isLoadingExist() {
  _loadTags.removeWhere((it) => !SmartDialog.checkExist(tag: it));
  return _loadTags.isNotEmpty;
}

///显示 loading
LoadingController showLoadingDialog({
  String? tag,
  String? msg,
  bool clickMaskDismiss = false,
  bool? backDismiss,
}) {
  final controller = LoadingController(initTag: tag, initMsg: msg); // 绑定唯一tag
  SmartDialog.show(
    tag: controller.tag,
    useAnimation: false,
    backType: backDismiss == null ? null : (backDismiss == true ? SmartBackType.normal : SmartBackType.block),
    builder: (ctx) => Obx(() => LoadingWidget(msg: controller.message.value)),
    onDismiss: () {
      _loadTags.remove(controller.tag);
    },
    maskColor: const Color.fromRGBO(0, 0, 0, 0.1),
    clickMaskDismiss: clickMaskDismiss,
  );
  _loadTags.add(controller.tag);
  return controller;
}

//隐藏 loading
Future hideLoadingDialog([String? tag]) {
  _loadTags.remove(tag);
  return SmartDialog.dismiss(tag: tag ?? _loadTags.lastOrNull);
}

//是否存在 loading
bool checkExist([String? tag]) {
  return SmartDialog.checkExist(tag: tag ?? _loadTags.lastOrNull);
}

// 创建状态管理类
class LoadingController {
  final String tag;

  // 响应式消息
  final RxString message;

  LoadingController({String? initTag, String? initMsg})
      : tag = initTag ?? (1000000 + Random().nextInt(999999)).toString(),
        message = RxString(initMsg ?? I18nKey.loading.trx);

  void updateMessage(String? msg) {
    message.value = msg ?? I18nKey.loading.trx;
  }

  bool isExist() {
    return checkExist(tag);
  }

  void dismiss() {
    hideLoadingDialog(tag);
  }
}

/// 自定义Loading框
class LoadingWidget extends StatelessWidget {
  const LoadingWidget({super.key, required this.msg});

  ///loading msg
  final String msg;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 20),
      decoration: BoxDecoration(
        color: ThemeStyle.backgroundColor,
        borderRadius: BorderRadius.circular(15),
      ),
      child: Column(mainAxisSize: MainAxisSize.min, children: [
        //loading animation
        CircularProgressIndicator(
          strokeWidth: 3,
          valueColor: AlwaysStoppedAnimation(ThemeStyle.textColor),
        ),

        //msg
        Container(
          margin: const EdgeInsets.only(top: 20),
          child: Text(msg, style: TextStyle(color: ThemeStyle.textColor)),
        ),
      ]),
    );
  }
}

class LoadingDialog {
  static Widget dialog({
    String msg = 'loading...',
  }) {
    return Container(
      width: 120,
      height: 120,
      alignment: Alignment.center,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          const SizedBox(
            width: 46,
            height: 46,
            child: CircularProgressIndicator(
              valueColor: AlwaysStoppedAnimation(ColorsApp.load_and_retry_circle_color),
              strokeWidth: 2,
            ),
          ),
          const SizedBox(
            height: 10,
          ),
          Offstage(
            offstage: false,
            child: Text(
              msg,
              style: const TextStyle(color: ColorsApp.load_and_retry_load_title_color, fontSize: 12),
            ),
          )
        ],
      ),
    );
  }
}
